package com.ctshk.rpc.visa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.visa.entity.VisaProduct;
import com.ctshk.rpc.visa.mapper.VisaProductMapper;
import com.ctshk.rpc.visa.req.visa.VisaProductSaveReq;
import com.ctshk.rpc.visa.service.IVisaProductService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 签证产品 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-01-28
 */
@DubboService
public class VisaProductServiceImpl extends ServiceImpl<VisaProductMapper, VisaProduct> implements IVisaProductService {
    @Autowired
    private VisaProductMapper visaProductMapper;

    @Override
    @Transactional
    public Long add(VisaProductSaveReq visaProductSaveReq, TokenUser user){
        VisaProduct visaProduct = new VisaProduct();
        if(visaProductSaveReq.getAdjustType() == 1){
            visaProduct.setAmount(visaProductSaveReq.getAmount());
        }else if(visaProductSaveReq.getAdjustType() == 2){
            visaProduct.setPercent(Math.ceil(visaProductSaveReq.getPercent()));
        }
        visaProduct.setAdjustType(visaProductSaveReq.getAdjustType());
        visaProduct.setIsDeleted(0);
        visaProduct.setSourceType(1);
        visaProduct.setCreateId(user.getId());
        visaProduct.setGmtCreate(LocalDateTime.now());
        visaProduct.setStatus(0);
        List<String> visaIds = visaProductSaveReq.getVisaId();
        Long id =0l;
        if(visaIds != null){
            for(String visaId : visaIds){
                visaProduct.setVisaId(Long.parseLong(visaId));
                id = SnowflakeIdWorker.nextId();
                visaProduct.setId(id);
                QueryWrapper<VisaProduct> visaProductQueryWrapper = new QueryWrapper<>();
                visaProductQueryWrapper.eq("visa_id",visaId);
                VisaProduct product = visaProductMapper.selectOne(visaProductQueryWrapper);
                if (product == null){
                    throw new BusinessException(SystemError.VISA_ORDER_25012);
                }
                visaProduct.setProductNum(product.getProductNum());
                visaProductMapper.delete(visaProductQueryWrapper);
                visaProductMapper.insert(visaProduct);
            }
        }
        return id;
    }

}
